# coding=utf-8
import sys

import demjson

import AM
import Conn
import DD
import JD


def newRecord(name, userID, JDurl, DDurl, AMurl):
    conn = Conn.getConn()
    cursor = conn.cursor()
    cursor.execute(
        "SELECT auto_increment FROM information_schema.`TABLES` WHERE TABLE_SCHEMA='outsider' AND TABLE_NAME='tb_product'")
    ID = cursor.fetchone()[0]

    JDData = None
    DDData = None
    AMData = None
    if (JDurl != None):
        JDData = JD.getCodeAndPrice(JDurl)
        JD.downloadPicture(JDurl, ID)
    if (DDurl != None):
        DDData = DD.getCodeAndPrice(DDurl)
        if (JDData == None): DD.downloadPicture(DDurl, ID)
    if (AMurl != None):
        AMData = AM.getCodeAndPrice(AMurl)

    insertSQL = "INSERT INTO TB_PRODUCT (Name,USER_ID"
    valueSQL = "('" + name +  "','" + userID + "'"
    recordSQL = "INSERT INTO TB_PRODUCT_RECORD (PRODUCT_ID"
    recordValueSQL = "('" + str(ID) + "'"

    if (JDurl != None):
        insertSQL = insertSQL + ",JDcode,JDurl"
        valueSQL = valueSQL + ",'" + JDData[0] + "','" + JDurl + "'"
        recordSQL = recordSQL + ",JD_price"
        recordValueSQL = recordValueSQL + ",'" + str(JDData[1]) + "'"

    if (DDurl != None):
        insertSQL = insertSQL + ",DDcode,DDurl"
        valueSQL = valueSQL + ",'" + DDData[0] + "','" + DDurl + "'"
        recordSQL = recordSQL + ",DD_price"
        recordValueSQL = recordValueSQL + ",'" + str(DDData[1]) + "'"
    if (AMurl != None):
        insertSQL = insertSQL + ",AMcode,AMurl"
        valueSQL = valueSQL + ",'" + AMData[0] + "','" + AMurl + "'"
        if (AMData[1]!=None):
         recordSQL = recordSQL + ",AM_price"
         recordValueSQL = recordValueSQL + ",'" + str(AMData[1]) + "'"
    if (JDurl != None or DDurl != None):
        insertSQL = insertSQL + ",PIC) "
        valueSQL = valueSQL + ",'" + str(ID) + ".jpg') "
    else:
        insertSQL = insertSQL + ") "
        valueSQL = valueSQL + ") "

    recordSQL = recordSQL + ",Date) "
    recordValueSQL = recordValueSQL + ",now()) "

    SQL = insertSQL + " VALUES " + valueSQL
    cursor.execute(SQL)
    conn.commit()


    SQL = recordSQL + " VALUES " + recordValueSQL
    cursor.execute(SQL)
    conn.commit()

    conn.close()

json=sys.argv[1]
print(json)
data=demjson.decode(json)
name=data['NAME']
userID=data['USERID']
JDurl=None
DDurl=None
AMurl=None
if ('JDURL' in data):
    JDurl=data['JDURL']
if ('DDURL' in data):
    DDurl=data['DDURL']
if ('AMURL' in data):
    AMurl=data['AMURL']
newRecord(name,userID,JDurl,DDurl,AMurl)
